package initialize

import (
	"fmt"
	"github.com/natefinch/lumberjack"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"strings"
	"time"
)

var (
	DB               *gorm.DB
	Log              *logrus.Logger
	SpecificCustomer string
)

func InitConfig() {
	viper.SetConfigName("app")
	viper.AddConfigPath(".")
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("config app init success。。")
	SpecificCustomer = viper.GetString("specificCustomer")
	fmt.Println(SpecificCustomer)
}

func InitMySQL() {
	// 从配置文件中读取数据库连接字符串
	dsn := viper.GetString("mysql.dsn")
	dbName := viper.GetString("mysql.dbName")

	if !strings.HasSuffix(dsn, "/") {
		dsn += "/"
	}

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			Colorful:                  true,
			IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
		},
	)
	// 添加 charset=utf8mb4 和 parseTime=true 参数
	dbName += "?charset=utf8mb4&parseTime=true&loc=Local"
	// 尝试连接到数据库
	db, err := gorm.Open(mysql.Open(dsn+dbName), &gorm.Config{Logger: newLogger})
	fmt.Println(dsn + dbName)
	if err != nil {
		// 如果连接失败，尝试创建数据库
		db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger})
		if err != nil {
			Log.Printf("failed to connect to MySQL server: %v", err)
		}
		// 创建数据库
		db.Exec("CREATE DATABASE " + dbName)
		// 重新连接到创建的数据库
		if !strings.HasSuffix(dsn, "/") {
			dsn += "/"
		}
		// 添加 charset=utf8mb4 和 parseTime=true 参数
		dbName += "?charset=utf8mb4&parseTime=true&loc=Local"

		DB, err = gorm.Open(mysql.Open(dsn+dbName), &gorm.Config{Logger: newLogger})
		if err != nil {
			Log.Printf("failed to reconnect to the new database: %v", err)

		}
		Log.Printf("Database '%s' created and connected successfully", dbName)
	} else {
		// 如果连接成功，使用该数据库
		DB = db
		Log.Printf("Connected to existing database '%s'", dbName)
	}

}

func InitLogrus() {
	log1 := logrus.New()
	// 创建一个文本格式化器并设置时间格式
	customFormatter := &logrus.TextFormatter{
		FullTimestamp:   true, // 显示完整时间戳
		TimestampFormat: "2006-01-02 15:04:05",
	}
	//使用lumberjack.Logger作为日志输出
	log1.SetOutput(&lumberjack.Logger{
		Filename:   "./logs/" + getCurrentDate() + ".log",
		MaxSize:    10,  //文件大小（MB）
		MaxBackups: 100, //最多备份文件数量
		MaxAge:     30,  //文件最长保存天数
		Compress:   false,
	})
	// 设置格式化器
	log1.Formatter = customFormatter
	log1.SetLevel(logrus.DebugLevel)
	Log = log1
}

func getCurrentDate() string {
	return time.Now().Format("2006-01-02")
}
